package scatter.wwd.rest.componentimpl.pay;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import scatter.common.dict.PublicDictEnums;
import scatter.dict.rest.service.IDictService;
import scatter.identifier.pojo.po.Identifier;
import scatter.identifier.rest.service.IIdentifierService;
import scatter.pay.rest.service.IWxOpenIdResolver;

/**
 * <p>
 * 微信三方下单时，获取用户openid
 * </p>
 *
 * @author yangwei
 * @since 2021-07-03 14:58
 */
@Slf4j
@Component
public class WxOpenIdResolverImpl implements IWxOpenIdResolver {

	@Autowired
	private IIdentifierService iIdentifierService;
	@Autowired
	private IDictService dictService;

	@Value("${wwd.wx.openId.resolve:}")
	private String wxOpenIdResolveForTest;

	@Override
	public String resolve(Type type, String userId, String appCode) {

		// 主要用于测试
		if (StrUtil.isNotEmpty(wxOpenIdResolveForTest)) {
			return "ocuui0k6MlNGkKEhaTBugJQ2LUDk";
		}
		if (Type.mp == type) {

			String dictId = dictService.getIdByGroupCodeAndValue(Identifier.TypeDictGroup.account_type.groupCode(), Identifier.TypeDictItem.wx_mp.itemValue());
			Identifier byUserIdAndIdentifierTypeDictId = iIdentifierService.getByUserIdAndIdentifierTypeDictIdAndGroupFlag(userId,dictId,PublicDictEnums.UserGroupFlagDictItem.wx_mp.name());

			if (byUserIdAndIdentifierTypeDictId != null) {
				return byUserIdAndIdentifierTypeDictId.getIdentifier();
			}else {
				log.warn("未获取到用户的openid，因查询UserIdentifier返回空，userId=[{}]",userId);
			}
		}
		log.warn("未获取到用户的openid，因不支付的类型，type=[{}]",type.name());
		return null;
	}
}
